from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QFileDialog, QDialog, QTableWidgetItem, QMessageBox, QHeaderView
from PySide6.QtCore import Signal, QThread, Qt
from PySide6.QtGui import QTextCursor
from logs.Log import Log

log = Log()


# 自定义历史路径选择框
# noinspection PyUnresolvedReferences
class SearchPathDialog:
    def __init__(self):
        self.dialog = QUiLoader().load('searchPathDialog.ui')

    def SetList(self, dataList):
        """
        设置历史路径\n
        :param dataList: 历史路径列表
        """
        self.dialog.pathListWidget.addItems(dataList)

    def ShowDialog(self):
        """
        展示窗口\n
        """
        self.dialog.exec()

    def GetListItem(self):
        """
        获取用户选择项\n
        """
        currentItem = self.dialog.pathListWidget.currentItem()
        if currentItem:
            return currentItem.text()
        else:
            return None


# 活动数据比对详细内容展示框
# noinspection PyUnresolvedReferences
class ShowDatalog:
    def __init__(self):
        self.datalog = QUiLoader().load('showdata.ui')
        self.datalog.setWindowFlag(Qt.WindowMinMaxButtonsHint)
        self.resourceScrollBar = self.datalog.resourceEdit.verticalScrollBar()
        self.targetScrollBar = self.datalog.targetEdit.verticalScrollBar()
        self.resourceScrollBar.valueChanged.connect(self.ScrollBarValueChange)

    def AddBackText(self, textEdit, text):
        """
        追加单行普通文本内容\n
        :param textEdit: textEdit控件对象
        :param text: 需要追加的文本内容
        """
        textEdit.setText(text)

    def AddRedText(self, textEdit, text):
        """
        追加单行普通文本内容\n
        :param textEdit: textEdit控件对象
        :param text: 需要设置富文本的文本内容
        """
        textEdit.setHtml(text)

    def ShowDialog(self):
        """
        展示窗口\n
        """
        self.datalog.exec()

    def ScrollBarValueChange(self, value):
        self.targetScrollBar.setValue(value)


# 自定义默认设置窗口
# noinspection PyUnresolvedReferences
class SettingDialog:
    def __init__(self):
        self.dialog = QUiLoader().load('setting.ui')

    def ShowDialog(self):
        """
        展示窗口\n
        """
        self.dialog.exec()

    def SetDatas(self, data):
        data.config.SetDefault()
        self.dialog.panleBox.addItems(data.config.panelList)
        self.dialog.excelBox.addItems(data.config.exclList)
        self.dialog.pathEdit.setText(data.config.configJson["默认路径"])
        self.dialog.colorEdit.setText(data.config.configJson["高亮颜色"])
        self.dialog.sizeEdit.setText(data.config.configJson["字体大小"])
        for text in data.config.configJson["历史路径"]:
            self.dialog.historyPathEdit.appendPlainText(text)

    def GetConfigItems(self):
        _list = [self.dialog.panleBox.currentText(),
                 self.dialog.excelBox.currentText(),
                 self.dialog.pathEdit.text(),
                 self.dialog.colorEdit.text(),
                 self.dialog.sizeEdit.text(),
                 self.dialog.historyPathEdit.toPlainText().splitlines()]
        return _list


# 各类 QT会话窗口
# noinspection PyTypeChecker
class OpenDialog(QDialog):
    def __init__(self):
        super(OpenDialog, self).__init__()

    # 路径选择框 QFileDialog
    def ShowDirectory(self):
        myDir = QFileDialog.getExistingDirectory(self, "请选择文件夹路径", "/home")
        return myDir

    # 提示对话框 QMessageBox
    def ShowMessage(self, text):
        # QMessageBox.critical(self, '错误', text)
        QMessageBox.about(self, 'Message', f"{text}     ")

    # 输入提示框 QInputDialog
    def ShowInput(self):
        pass


class BackendThread(QThread):
    command = Signal(str)

    def __init__(self, parent=None):
        super(BackendThread, self).__init__(parent)
        self.text = None

    def SetText(self, text):
        self.text = text

    # noinspection PyUnresolvedReferences
    def run(self):
        self.command.emit(self.text)


class LableView:
    def __init__(self):
        self.okColor = "49, 54, 59"
        self.okBackgrundColor = "29, 233, 182"
        self.errColor = "255, 255, 255"
        self.errBackgrundColor = "70, 119, 255"
        self.workColer = '30, 39, 46'
        self.workBackgrundColor = '254, 211, 48'
        self.style = None
        self.lable = None
        self.backendThread = BackendThread()

    def SetOk(self, color, backgrund):
        self.okColor = color
        self.okBackgrundColor = backgrund

    def SetErr(self, color, backgrund):
        self.errColor = color
        self.errBackgrundColor = backgrund

    def SetText(self, text):
        self.lable.setText(f"<<<<<<<<< {text} >>>>>>>>>>")
        self.lable.setStyleSheet(self.style)

    # noinspection PyUnresolvedReferences
    def ShowLable(self, lable, text, showType=0):
        """
        展示比对结果\n
        :param lable: Qlable对象
        :param text: 展示的内容
        :param showType: 展示的结果类型，0为正常，1为异常
        """
        if showType == 0:
            self.style = 'QLabel{color: rgb(%s);background-color: rgb(%s);}' \
                         % (self.okColor, self.okBackgrundColor)
        elif showType == 1:
            self.style = 'QLabel{color: rgb(%s);background-color: rgb(%s);}' \
                         % (self.errColor, self.errBackgrundColor)
        elif showType == 2:
            self.style = 'QLabel{color: rgb(%s);background-color: rgb(%s);}' \
                         % (self.workColer, self.workBackgrundColor)
        else:
            self.style = 'QLabel{}'

        self.lable = lable
        self.backendThread.SetText(text)
        self.backendThread.command.connect(self.SetText)
        self.backendThread.start()


# tableWidger相关
class TableWidgetView:
    @staticmethod
    def SetHorizontalSize(qTableWidget, htype=0):
        """
        设置列狂展示模式\n
        0：Stretch 用户不可调整,【内容自动平分】\n
        1：ResizeToContents 用户不可调整,【内容自动适应】\n
        2：Fixed 用户不可调整，【固定为默认值】\n
        3：Interactive 用户【可调整】\n
        4：Custom 用户【可调整】\n
        :param qTableWidget: qTableWidget 对象
        :param htype: 列宽的展示方式
        :return:
        """
        if htype == 0:
            # 用户不可调整,【自动平分】适应可用区域
            qTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        elif htype == 1:
            # 用户不可调整,【自动适应】内容的宽度
            qTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        elif htype == 2:
            # 用户不可调整，【固定为默认值】默认值为setDefaultSectionSized的值
            qTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
        elif htype == 3:
            # 用户【可调整】，默认值为setDefaultSectionSized的值
            qTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        elif htype == 4:
            # 用户【可调整】,默认值为setDefaultSectionSized的值
            qTableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Custom)
        qTableWidget.horizontalHeader().setDefaultSectionSize(100)

    @staticmethod
    def ShowDifferent(qTableWidget, dataList):
        """
        规划差异内容展示\n
        :param qTableWidget: TableWidget 控件对象
        :param dataList: 需要展示的数据
        """
        if dataList:
            qTableWidget.clear()  # 清空表格内容，包括头部
            qTableWidget.setRowCount(len(dataList))  # 设置行数，不包括头部
            qTableWidget.setColumnCount(1)  # 设置列数
            qTableWidget.setHorizontalHeaderLabels(("比对结果",))
            # 列宽自适应
            TableWidgetView.SetHorizontalSize(qTableWidget)
            for row in range(len(dataList)):
                item = QTableWidgetItem(str(dataList[row]))  # 生成表格单元格数据
                qTableWidget.setItem(row, 0, item)  # 设置单元格位置
        else:
            qTableWidget.clear()  # 清空表格内容，包括头部
            qTableWidget.setRowCount(1)  # 设置行数，不包括头部
            qTableWidget.setColumnCount(1)  # 设置列数
            # 列宽自适应
            TableWidgetView.SetHorizontalSize(qTableWidget)
            qTableWidget.setHorizontalHeaderLabels(("比对结果",))
            item = QTableWidgetItem("结果无差异")
            qTableWidget.setItem(0, 0, item)  # 设置单元格位置

    @staticmethod
    def ShowTableData(obj, searchList, reader, show=0):
        """
        单个表格查询数据展示\n
        :param reader: reader对象
        :param obj: TableWidget 控件对象
        :param searchList: 需要搜索的列表
        :param show: 0为普通数据查询，1为活动数据查询
        """

        def ClearAndRow(qTableWidget, headers, row=1, column=1):
            """
            单表查询，设置表头
            """
            qTableWidget.clear()  # 清空表格内容，包括头部
            # qTableWidget.clearContents()  # 清空表格内容，不包括头部
            qTableWidget.setRowCount(row)  # 设置行数，不包括头部
            if headers:
                qTableWidget.setColumnCount(len(headers))  # 设置列数
                qTableWidget.setHorizontalHeaderLabels(headers)
                # 设置列宽
                TableWidgetView.SetHorizontalSize(qTableWidget, 3)
            else:
                qTableWidget.setColumnCount(column)  # 设置列数
                # 设置列宽
                TableWidgetView.SetHorizontalSize(qTableWidget, 3)

        def ShowTable(qTableWidget, dataList, headers):
            """
            单表查询，展示数据内容
            """
            if dataList:
                column = 1
                _row = len(dataList)
                if not headers:
                    column = len(dataList[0])
                log.Show(_row, 20, "ShowTable > lenght")
                ClearAndRow(qTableWidget, headers, _row, column)
                TableWidgetView.SetItem(qTableWidget, dataList, _row)
            else:
                ClearAndRow(qTableWidget, headers)
                item = QTableWidgetItem(">>>>查无数据<<<<")
                # item.setForeground(QBrush(QColor(230, 230, 230)))
                qTableWidget.setItem(0, 0, item)

        # ===============================================================
        if show == 0:
            # 判断读取类是否为空
            if reader:
                # 非空时获取数据列表
                dataList = reader.GetDataList(searchList, searchList[0])
            else:
                dataList = None
            # 展示查询数据
            ShowTable(obj, dataList, reader.headers)
        if show == 1:
            if reader:
                # 非空时获取数据列表
                dataList = reader.GetActivityList(searchList)
            else:
                dataList = None
            # 展示查询数据
            ShowTable(obj, dataList, None)

    @staticmethod
    def SetItem(qTableWidget, dataList, lenght):
        """
        设置数据展示内容\n
        :param qTableWidget: qTableWidget 对象
        :param dataList: 需要展示的一维列表
        :param lenght: 数据的行数
        """
        for row in range(lenght):
            if type(dataList[row]) is tuple:
                for column in range(len(dataList[row])):
                    item = QTableWidgetItem(dataList[row][column])  # 生成表格单元格数据
                    # item.setForeground(QBrush(QColor(230, 230, 230)))  # 设置单元格字体颜色
                    if column == 0:
                        if dataList[row][0] == "查无数据":
                            pass
                            # item.setForeground(QBrush(QColor(0, 180, 255)))
                            # item.setBackground(QBrush(QColor(0, 180, 255)))
                    qTableWidget.setItem(row, column, item)  # 设置单元格位置
            else:
                item = QTableWidgetItem(dataList[row])
                # item.setForeground(QBrush(QColor(230, 230, 230)))
                qTableWidget.setItem(row, 0, item)


class QPlainTextSelect:
    @staticmethod
    def SetTextSelect(qPlainTextEdit, lines, Left, Right):
        textCursor = qPlainTextEdit.textCursor()
        textCursor.movePosition(QTextCursor.MoveOperation.Start)
        textCursor.movePosition(QTextCursor.MoveOperation.Down, QTextCursor.MoveMode.MoveAnchor, lines)
        textCursor.movePosition(QTextCursor.MoveOperation.Left, QTextCursor.MoveMode.MoveAnchor, Left)
        textCursor.movePosition(QTextCursor.MoveOperation.Right, QTextCursor.MoveMode.KeepAnchor, Right)
        qPlainTextEdit.setTextCursor(textCursor)
